package com.maxus.mini.ecard.open.api.controller.user;

import java.text.MessageFormat;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.maxus.mini.common.Constants;
import com.maxus.mini.common.WechatConstants;
import com.maxus.mini.common.utils.BeanUtilsExtended;
import com.maxus.mini.common.utils.HttpRequest;
import com.maxus.mini.common.vo.ResBody;
import com.maxus.mini.ecard.data.api.redis.RedisService;
import com.maxus.mini.ecard.data.api.user.UserService;
import com.maxus.mini.ecard.entity.user.User;
import com.maxus.mini.ecard.open.api.controller.BaseController;
import com.maxus.mini.ecard.open.api.vo.req.P100000Vo;
import com.maxus.mini.ecard.open.api.vo.req.P800000Vo;
import com.maxus.mini.ecard.open.api.vo.res.PR800000Vo;
import com.maxus.mini.ecard.open.api.vo.res.WechatVo;

/**
 * 用户controller
 * 
 * @author wujinsong
 *
 */
@RestController()
@RequestMapping(value = "api/v1.0/user")
public class UserController extends BaseController {
	@Reference(version = "1.0.0")
	private UserService<User, User> userService;
	@Reference(version = "1.0.0")
	private RedisService redisService;

	/**
	 * 保存用户
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "save")
	@ResponseBody()
	public User save(P100000Vo req) {
		User user = userService.findByOpenid(req.getOpenid());
		if (user != null) {
			return user;
		}
		user = new User();
		BeanUtilsExtended.copyProperties(user, req);

		return userService.save(user);
	}

	/**
	 * code换取 session_key接口
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "jscode2session")
	@ResponseBody()
	public ResBody jscode2session(P800000Vo req) {
		PR800000Vo retVo = new PR800000Vo();

		String surl = MessageFormat.format(WechatConstants.jscode2session, WechatConstants.ecard_appid,
				WechatConstants.ecadr_secret, req.getCode());
		String res = HttpRequest.get(surl);
		WechatVo wechatVo = Constants.GSON.fromJson(res, WechatVo.class);
		if (StringUtils.isEmpty(wechatVo.getErrcode())) {
			try {
				retVo = Constants.GSON.fromJson(res, PR800000Vo.class);
			} catch (Exception e) {
				retVo.setStatus(wechatVo.getErrcode());
				retVo.setMemo(wechatVo.getErrmsg());
			}
		} else {
			retVo.setStatus(wechatVo.getErrcode());
			retVo.setMemo(wechatVo.getErrmsg());
		}

		return retVo;
	}

	/**
	 * 获取用户
	 * 
	 * @param users
	 * @return
	 */
	public Iterable<User> save(List<User> users) {
		return userService.save(users);
	}
}
